package com.tsk.state.test;

import lombok.Setter;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.statemachine.state.State;

import java.util.UUID;

/**
 * @author: 黄嘉振
 * @create: 2023/5/25 17:13
 * @description:
 **/
public class StatemachineService<S,E,T> {
    @Setter
    private StateMachinePersister<S, E, T> setStateMachinePersister;
    @Setter
    private StateMachineFactory<S, E> stateMachineFactory;

    public S getState(T data) {
        StateMachine<S, E> stateMachine = stateMachineFactory.getStateMachine(UUID.randomUUID());
        stateMachine.start();
        try {
            setStateMachinePersister.restore(stateMachine, data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        State<S, E> state = stateMachine.getState();
        return state.getId();
//        return stateMachine;
    }
    public boolean execute(T data, E event) throws Exception {
        // 利用随记ID创建状态机，创建时没有与具体定义状态机绑定
        StateMachine<S, E> stateMachine = stateMachineFactory.getStateMachine(UUID.randomUUID());
        stateMachine.start();
        boolean success = false;
        try {
            setStateMachinePersister.restore(stateMachine, data);
            // 发送事件，返回是否执行成功
            success = stateMachine.sendEvent(event);
            if (success) {
                System.out.println("persist begin!id={" + data + "},event={ " + event + "}");
                // 持久化
                setStateMachinePersister.persist(stateMachine, data);
                System.out.println("persist end!id={" + data + "},event={ " + event + "}");
            } else {
                System.out.println("id={" + data + "},event={ " + event + "} send Event fail");
            }
        } catch (Exception e) {
            System.out.println("id={" + data + "},event={ " + event + "} ,state machine execute error");
            throw e;
        } finally {
            stateMachine.stop();
        }
        return success;
    }
}
